package www.openteam.com.workorder;


import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.OTApplication;
import www.openteam.com.R;
import www.openteam.com.base.OtherBaseFragment;
import www.openteam.com.bean.GroupCount;
import www.openteam.com.bean.Inputer;
import www.openteam.com.bean.MachineInfo;
import www.openteam.com.bean.PDistrubition;
import www.openteam.com.bean.RequstMaterial;
import www.openteam.com.bean.UpdateInfo;
import www.openteam.com.bean.WorkOrder2;
import www.openteam.com.tool.EditTextShakeTool;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.business.ScanActivity;
import www.openteam.com.ui.business.other.PSearchFragment;
import www.openteam.com.ui.business.other.WOSearchFragment;
import www.openteam.com.widget.ItemRemoveRecycleView;

/**
 * Created by kylin on 2017/4/27.
 */

public class ZZWorkOrderFragment extends OtherBaseFragment<ZZWorkOrderPresenter> implements
        ZZWorkOrderContract.WorkOrderView {


    private static final String TAG = ZZWorkOrderFragment.class.getSimpleName();
    @Bind(R.id.et_inputer)
    EditText et_inputer;
    @Bind(R.id.et_work_order_id)
    EditText et_work_order_id;
    @Bind(R.id.et_s_time)
    EditText et_s_time;
    @Bind(R.id.et_machine_id)
    EditText et_machine_id;
    @Bind(R.id.et_e_time)
    EditText et_e_time;
    @Bind(R.id.et_order_id)
    EditText et_order_id;
    @Bind(R.id.et_cust_name)
    EditText et_cust_name;
    @Bind(R.id.et_partId)
    EditText et_partId;
    @Bind(R.id.et_procedure)
    EditText et_procedure;
    @Bind(R.id.et_product_name)
    EditText et_product_name;
    @Bind(R.id.et_should_num)
    EditText et_should_num;
    @Bind(R.id.et_already_num)
    EditText et_already_num;
    @Bind(R.id.et_produce_num)
    EditText et_produce_num;
    @Bind(R.id.et_no_finish_num)
    EditText et_no_finish_num;
    //    @Bind(R.id.et_team_group)
//    EditText et_team_group;
//    @Bind(R.id.et_people_group)
//    EditText et_people_group;
    //    @Bind(R.id.btn_add)
//    Button btn_add;
    @Bind(R.id.btn_cancel)
    Button btn_cancel;
    @Bind(R.id.btn_keep)
    Button btn_keep;
    //    @Bind(R.id.btn_delete)
//    Button btn_delete;
    @Bind(R.id.et_remark)
    EditText et_remark;
    //    @Bind(R.id.bt_w_delete)
//    Button bt_w_delete;
    @Bind(R.id.btn_inpter)
    Button btn_inpter;
    @Bind(R.id.iv_scan)
    ImageView iv_scan;
    @Bind(R.id.iv_scan_jt)
    ImageView iv_scan_jt;
    @Bind(R.id.cb_is_finish)
    CheckBox cb_is_finish;


    private Intent intent;
    int RESULT_WO_ID = 1111;
    int RESULT_WO_MID = 1112;
    EditTextShakeTool editTextShakeTool;
    private double alreadyNum;
    private double nofinishNum;
    private double thisAllow;
    private String procno = "";
    SharedPreferences workSP = OTApplication.getmContext().getSharedPreferences("wk",
            getContext().MODE_PRIVATE);
    public Resources resources;
    private boolean isFinal = false;
    private ItemRemoveRecycleView itemRemoveRecycleView;
    private ArrayList<GroupCount> groupCount;
    private int sheetNumb;
    List<WorkOrder2.DataBeanX.DataBean> realHandleWorkOrder;
    private String machine_id;
    private String work_id;
    private String machine_code = "";

    //    private ImageButton add_item;
    private int count = 0;
    private FragmentManager manager;
    private FragmentTransaction ft;
    private WOSearchFragment woSearchFragment;
    private PSearchFragment pSearchFragment;
    private Bundle args;
    private ZZWorkAdapter adapter;
    private boolean isExist = false;
    private boolean isFinish = false;
    private String inpuer;
    private int barZbid;
    private boolean isInputer = false;
    private boolean isWorkId = false;
    private boolean isMachineInfo = false;
    private int id;
    private LinearLayoutManager linearLayoutManager;
    private ArrayAdapter<String> printTypeAdapter;
    private ArrayAdapter<String> printPoNeAdapter;
    private ArrayAdapter<String> emptyAdapter;
    private ArrayList<PDistrubition.DataBeanX.DataBean> pdistrubition;
    private String mId;
    private String isOver;


    @Override
    protected void initData() {
        Log.e(TAG, "initData: ");
        resources = getResources();
        ArrayList<String> printTypeList = new ArrayList<>();
        printTypeList.add("正翻");
        printTypeList.add("自翻");
        printTypeList.add("滚翻");
        printTypeList.add("双面");
        printTypeAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, printTypeList);
        printTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ArrayList<String> printPoNeList = new ArrayList<>();
        printPoNeList.add("正面");
        printPoNeList.add("反面");
        printPoNeAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, printPoNeList);
        printPoNeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        emptyAdapter = new ArrayAdapter<String>
                (getContext(), android.R.layout.simple_spinner_item);
//        mProgressDialog = new ProgressDialog(getContext());
        et_inputer.setText(mySetting.getString("mCode", ""));
    }


    @Override
    protected void initListener() {
//        btn_add.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
//        btn_delete.setOnClickListener(this);
//        bt_w_delete.setOnClickListener(this);
        btn_keep.setOnClickListener(this);
        iv_scan.setOnClickListener(this);
        btn_inpter.setOnClickListener(this);
        iv_scan_jt.setOnClickListener(this);
//        add_item.setOnClickListener(this);
//        et_people_group.setOnClickListener(this);
        /**
         * 20170518 去掉班组
         */
//        et_team_group.setOnClickListener(this);
        et_produce_num.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                int tJudge = 0;
                tJudge = realHandleWorkOrder.get(0).getIsPrint() == 1 ? 1 : 3;  // ?a:b
                tJudge += realHandleWorkOrder.get(0).getIsTake() == 1 ? 8 : 2;   //?c:d
                // 只是打印不领料 a+d 3,  只是领料不打印 b+c 11 ,
                // 又是打印,又领料 a+c,9  既不是打印也不领料 b+d; 5
                double max;
                double inp;
                double min;
                switch (tJudge) {
                    case 3:
                        max = Integer.valueOf(realHandleWorkOrder.get(0).getAddPaper()) + nofinishNum;
                        inp = Double.parseDouble(et_produce_num.getText().toString());
                        et_produce_num.setText(getMin(max, inp) + "");
                        Log.d(TAG, "onEditorAction: " + (thisAllow - getMin(max, inp)));
                        et_no_finish_num.setText(thisAllow - getMin(max, inp) + "");
                        break;
                    case 5:
                        inp = Double.parseDouble(et_produce_num.getText().toString());
                        et_produce_num.setText(getMin(nofinishNum, inp) + "");
                        et_no_finish_num.setText(thisAllow - getMin(nofinishNum, inp) + "");
                        Log.d(TAG, "onEditorAction: " + (thisAllow - getMin(nofinishNum, inp)));
                        break;
                    case 9:
                        if (sheetNumb > 0) {
                            max = Integer.valueOf(realHandleWorkOrder.get(0).getAddPaper()) + nofinishNum;
                            inp = Double.parseDouble(et_produce_num.getText().toString());
                            min = getMin(max, sheetNumb);
                            et_produce_num.setText(getMin(min, inp) + "");
                            et_no_finish_num.setText(thisAllow - getMin(min, inp) + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - thisAllow - getMin(min, inp)));
                        } else {
                            ToastUtil.showToast(getContext(), resources.getString(R.string.takeMetral_hint));
                            et_produce_num.setText(0 + "");
                            et_no_finish_num.setText(thisAllow - 0 + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - 0));
                        }
                        break;
                    case 11:
                        if (sheetNumb > 0) {
                            inp = Double.parseDouble(et_produce_num.getText().toString());
                            min = getMin(nofinishNum, sheetNumb);
                            et_produce_num.setText(getMin(min, inp) + "");
                            et_no_finish_num.setText(thisAllow - getMin(min, inp) + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - getMin(min, inp)));
                        } else {
                            ToastUtil.showToast(getContext(), resources.getString(R.string.takeMetral_hint));
                            et_produce_num.setText(0 + "");
                            et_no_finish_num.setText(thisAllow - 0 + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - 0));
                        }
                        break;
                }


                return false;
            }
        });

        cb_is_finish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                isFinish = isChecked;
            }
        });
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, view);
        manager = getFragmentManager();
//        add_item = (ImageButton) view.findViewById(R.id.add_item);
//        itemRemoveRecycleView = (ItemRemoveRecycleView) view.findViewById(R.id.rv_wor);
        linearLayoutManager = new LinearLayoutManager(getActivity());
//        itemRemoveRecycleView.setLayoutManager(linearLayoutManager);
    }


    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected ZZWorkOrderPresenter loadPresenter() {
        return new ZZWorkOrderPresenter();
    }

    @Override
    public void onRefresh() {

    }


    private double getMin(double a, double b) {

        double min = a;
        if (a > b) {

            min = b;

        }

        return min;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String work_order_id = data.getStringExtra("work_order_id");
        String inputer = workSP.getString("inputer", "");
        if (inputer.isEmpty()) {
            ToastUtil.showToast(getContext(), "请确认录入员");
        } else {
            if (requestCode == RESULT_WO_ID && !work_order_id.equals("")) {
                mProgressDialog.show();
                workSP.edit().putString("work_id", work_order_id).commit();
                mPresenter.queryWO(work_order_id, getStype(), getMoreCom(),
                        mySetting.getInt(mId, 0));
            } else if (requestCode == RESULT_WO_MID && !work_order_id.equals("")) {
                mProgressDialog.show();
//            workSP.edit().putString("procno", procno).commit();
//            machine_id = work_order_id + "-" + procno;
                machine_id = work_order_id;
                machine_code = machine_id;
                mPresenter.findMachine(machine_id,
                        inputer, workSP.getString("procno", ""),
                        et_work_order_id.getText().toString(), getStype(), getMoreCom());
            }
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_work_order_zz;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.btn_add:
//                ToastUtil.showToast(OTApplication.getContext(), "add");
//                break;
            case R.id.btn_keep:
                keepTheData(isExist);
                break;
            case R.id.btn_cancel:
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                alertDialog.setTitle(resources.getString(R.string.work_order_cancel));
                alertDialog.setMessage(resources.getString(R.string.message_empty));
                alertDialog.setPositiveButton(resources.getText(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        emptyEt();
                    }
                });
                alertDialog.setNegativeButton(resources.getText(R.string.cancel), null);
                alertDialog.show();
                break;
//            case R.id.btn_delete:
//                ToastUtil.showToast(OTApplication.getContext(), "btn_delete");
//                break;
            //班组人组联合搜索
//            case R.id.bt_w_delete:
//                if (et_inputer.getText().toString().equals("") &&
//                        !isInputer) {
//                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_inputer_hint));
//                    new EditTextShakeTool(getActivity()).shake(et_inputer);
//                    et_inputer.setFocusable(true);
//                } else if (et_work_order_id.getText().toString().equals("") &&
//                        !isWorkId) {
//                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_id_hint));
//                    new EditTextShakeTool(getActivity()).shake(et_work_order_id);
//                    et_inputer.setFocusable(true);
//                } else if (et_machine_id.getText().toString().equals("") &&
//                        !isMachineInfo) {
//                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_machine_hint));
//                    new EditTextShakeTool(getActivity()).shake(et_machine_id);
//                    et_inputer.setFocusable(true);
//                }
//                else if (!et_people_group.getText().toString().equals("")) {
//                    mProgressDialog.show();
//                    mPresenter.findWorkPrice(workSP.getString("machine_id", ""),
//                            et_team_group.getText().toString(),
//                            et_people_group.getText().toString(), getStype(), getMoreCom());
//                }
//                else {
//                    ToastUtil.showToast(getContext(), resources.getString(R.string.peoplenotnull));
//                }
//                break;
            case R.id.iv_scan:
                iv_scan.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                if (et_inputer.getText().toString().equals("") &&
                        !isInputer) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_inputer_hint));
                    new EditTextShakeTool(getActivity()).shake(et_inputer);
                    et_inputer.setFocusable(true);
                } else {
                    if (et_work_order_id.getText().toString().equals("")) {
                        intent = new Intent(getActivity(), ScanActivity.class);
                        startActivityForResult(intent, RESULT_WO_ID);
                    } else if (!et_work_order_id.getText().toString().equals("")
                            && !isWorkId) {
                        mProgressDialog.show();
                        work_id = et_work_order_id.getText().toString();
                        mPresenter.queryWO(et_work_order_id.getText().toString(), getStype(), getMoreCom(),
                                mySetting.getInt("mId", 0));
                    } else {
                        ToastUtil.showToast(getContext(), resources.getString(R.string.cancel_hint));
                    }
                }

                break;
            case R.id.iv_scan_jt:
//                Log.d(TAG, "onClick: " + workSP.getString("machine_id", "").equals("") + ":" +
//                        !et_machine_id.getText().toString().equals(""));
                String searchInputer = workSP.getString("inputer", "");

                if (searchInputer.equals("") && isInputer) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_inputer_hint));
                    new EditTextShakeTool(getActivity()).shake(et_inputer);
                    et_inputer.setFocusable(true);
                } else if (et_work_order_id.getText().toString().equals("") &&
                        !isWorkId) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_id_hint));
                    new EditTextShakeTool(getActivity()).shake(et_work_order_id);
                    et_inputer.setFocusable(true);
                } else {
                    if (et_machine_id.getText().toString().equals("")) {
                        intent = new Intent(getActivity(), ScanActivity.class);
                        startActivityForResult(intent, RESULT_WO_MID);
                    } else if (!et_machine_id.getText().toString().equals("")
                            && !isMachineInfo) {
                        mProgressDialog.show();
                        //machine_id = et_machine_id.getText().toString() + "-" + procno;

                        machine_id = et_machine_id.getText().toString();
                        machine_code = et_machine_id.getText().toString();
                        mPresenter.findMachine(machine_id,
                                searchInputer,
                                workSP.getString("procno", ""),
                                et_work_order_id.getText().toString(), getStype(), getMoreCom());
                    } else {
                        ToastUtil.showToast(getContext(), resources.getString(R.string.cancel_hint));
                    }
                }

                break;
            case R.id.btn_inpter:
                queryWO();
                break;
//            case R.id.add_item:
//                pSearchFragment = new PSearchFragment();
//                Bundle arg = new Bundle();
//                ft = manager.beginTransaction();
//                ft.hide(this).add(R.id.fragment_container, pSearchFragment, "pSearchFragment");
//                ft.addToBackStack(null);
//                ft.commit();
//                pSearchFragment.theOkClick(new PSearchFragment.ButtonOkClick() {
//                    @Override
//                    public void returnWorker(PDistrubition.DataBeanX.DataBean DataEntity) {
//                        PDistrubition.DataBeanX.DataBean dataEntity1;
//                        if (adapter == null) {
//                            //如果adpter==null 。就要初始化apdater 和 pdistrubition
//                            adapter = new ZZWorkAdapter(getContext());
//                            adapter.addContext(getContext());
//                            pdistrubition = new ArrayList<>();
//                            dataEntity1 = new PDistrubition.DataBeanX.DataBean();
//                            dataEntity1.setId(1);
//                            dataEntity1.setCode(DataEntity.getCode());
//                            dataEntity1.setJob(DataEntity.getJob());
//                            dataEntity1.setName(DataEntity.getName());
//
//                            pdistrubition.add(dataEntity1);
//                            adapter.addItems(pdistrubition);
//                            itemRemoveRecycleView.setAdapter(adapter);
//                            itemRemoveRecycleView.setOnItemClickListener(new ItemRemoveRecycleView.ItemOnListener() {
//                                @Override
//                                public void onItemDelete(int position) {
//
//                                    adapter.removeItem(position);
//                                    pdistrubition.remove(position);
//                                    itemRemoveRecycleView.removeViewAt(position);
//
//                                }
//                            });
//                        } else {
//                            dataEntity1 = new PDistrubition.DataBeanX.DataBean();
//                            dataEntity1.setId(pdistrubition.size());
//                            dataEntity1.setCode(DataEntity.getCode());
//                            dataEntity1.setJob(DataEntity.getJob());
//                            dataEntity1.setName(DataEntity.getName());
//                            boolean isE = false;
//                            for (int i = 0; i < pdistrubition.size(); i++) {
//                                if (DataEntity.getCode().equals(pdistrubition.get(i).getCode())) {
//                                    isE = true;
//                                    break;
//                                }
//                            }
//                            if (isE) {
//                                ToastUtil.showToast(getContext(), "不能重复选择");
//                            } else {
//                                pdistrubition.add(dataEntity1);
//                                adapter.addItem(dataEntity1);
//                            }
//                            itemRemoveRecycleView.setOnItemClickListener(new ItemRemoveRecycleView.ItemOnListener() {
//                                @Override
//                                public void onItemDelete(int position) {
//
//                                    adapter.removeItem(position);
//                                    pdistrubition.remove(position);
//                                    itemRemoveRecycleView.removeViewAt(position);
//
//                                }
//                            });
//                        }
//
//                    }
//                });
//                break;
//            case R.id.et_people_group:
//                woSearchFragment = new WOSearchFragment();
//                Bundle args = new Bundle();
//                args.putInt("position", 1);
//                args.putString("mark", "查询人组");
//                woSearchFragment.setArguments(args);
//                woSearchFragment.buttonSetOnclick(new WOSearchFragment.ButtonSelect() {
//                    @Override
//                    public void buttonOnclickSelect(PeopleGroup.DataEntity peopleGroup, int position) {
//                        ft = manager.beginTransaction();
//                        ft.remove(woSearchFragment).show(ZZWorkOrderFragment.this);
//                        ft.addToBackStack(null);
//                        ft.commit();
//                        et_people_group.setText(peopleGroup.getGroupcount().toString());
//                    }
//                });
//                args.putString("searchCondition", workSP.getString("machine_id", "").toString());
//                ft = manager.beginTransaction();
//                ft.hide(this).add(R.id.fragment_container, woSearchFragment, "woSearchFragment");
//                ft.addToBackStack(null);
//                ft.commit();
//
//                break;
//            /**
//             * 20170518
//             * 去掉班组查询
//             */
//            case R.id.et_team_group:
//                woSearchFragment = new WOSearchFragment();
//                args = new Bundle();
//                args.putInt("position", 2);
//                args.putString("mark", "查询班组");
//                woSearchFragment.setArguments(args);
//                woSearchFragment.buttonSetOnclick(new WOSearchFragment.ButtonSelect() {
//                    @Override
//                    public void buttonOnclickSelect(PeopleGroup.DataEntity peopleGroup, int position) {
//                        ft = manager.beginTransaction();
//                        ft.remove(woSearchFragment).show(ZZWorkOrderFragment.this);
//                        ft.addToBackStack(null);
//                        ft.commit();
//                        et_team_group.setText(peopleGroup.getGroupcount().toString());
//                    }
//                });
//                args.putString("searchCondition", workSP.getString("machine_id", "").toString());
//                ft = manager.beginTransaction();
//
//                ft.hide(this).add(R.id.fragment_container, woSearchFragment, "woSearchFragment");
//                ft.addToBackStack(null);
//                ft.commit();
//                break;
//            default:
//                otherViewClick(view);
//                break;
        }

    }

    private int stringToNumb(String sumnub) {
        return Integer.valueOf(sumnub.isEmpty() ? "0" : sumnub);
    }

    private Double stringToNumbD(String sumnub) {
        return Double.valueOf(null == sumnub || sumnub.equals(".0000") ? "0" : sumnub);
    }

    //存档时数据检查
    private void keepTheData(boolean isExist) {

        int userid = mySetting.getInt("mId", 0);
        String mName = mySetting.getString("mName", "");
        String procno = workSP.getString("procno", "");
        long sTime = workSP.getLong("sTime", 0L);
        String inpter = workSP.getString("inputer", "");
        String machine_id = workSP.getString("machine_id", "");
        String inputerName = workSP.getString("inputerName", "");
        long eTime = workSP.getLong("eTime", 0L);
        WorkOrder2.DataBeanX.DataBean rw = null;
        if (realHandleWorkOrder != null) {
            rw = realHandleWorkOrder.get(0);
        }

        Log.d(TAG, "keepTheData: " + userid + ":" + sTime + ":" + inpter + ":" + machine_id);
        if (isExist) {
//            if (pdistrubition != null) {
            String produce_num = et_produce_num.getText().toString();
            if (null == isOver || "".equals(isOver) || isOver.equals("1")) {
//                1：输入生产数不允许大于未生产数，null默认为1
//                0：输入生产数允许大于未生产数
                if (!produce_num.equals("") && Double.parseDouble(produce_num) <= nofinishNum) {
                    groupCount = new ArrayList<>();
                    int num = 0;

//                    for (int i = 0; i < pdistrubition.size(); i++) {
//
//                        GroupCount gp = new GroupCount();
//                        gp.setId(i);
//                        gp.setZbid(barZbid + "");
//                        gp.setEmployeeCode(pdistrubition.get(i).getCode());
//                        gp.setDistributRate(pdistrubition.get(i).getDistributRate());
//                        gp.setProdNumb(Double.parseDouble(produce_num));
//                        Log.d(TAG, "keepTheData: " + pdistrubition.get(i).getCode() + ":" + pdistrubition.get(i).getName());
//                        groupCount.add(gp);
//                    }
//                    Gson gson = new Gson();
//                    String str = gson.toJson(groupCount); //
////                String str = ""; //
//                    try {
//                        str = URLEncoder.encode(str, "UTF-8");
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                    }

                    createProgressDialog(resources.getString(R.string.keeping));
//                    machine_code = "";
                    mPresenter.insertEProductionInfo("", isFinish, rw.getRdsno(),
                            "",
                            rw.getZbid(), eTime, eTime, rw.getPrdid() + "",
                            Double.parseDouble(produce_num),
                            machine_id, rw.getCode(), inpter, rw.getProcno(), rw.getCustid(), rw.getOrderno()
                            , Double.parseDouble(et_should_num.getText().toString())
                            , rw.getPartid(), mName, inputerName, userid, id, "",
                            getStype(), getMoreCom(), et_remark.getText().toString());


                } else {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.producenum));
                }
            } else {
                createProgressDialog(resources.getString(R.string.keeping));
//                    machine_code = "";
                mPresenter.insertEProductionInfo("", isFinish, rw.getRdsno(),
                        "",
                        rw.getZbid(), eTime, eTime, rw.getPrdid() + "",
                        Double.parseDouble(produce_num),
                        machine_id, rw.getCode(), inpter, rw.getProcno(), rw.getCustid(), rw.getOrderno()
                        , Double.parseDouble(et_should_num.getText().toString())
                        , rw.getPartid(), mName, inputerName, userid, id, "",
                        getStype(), getMoreCom(), et_remark.getText().toString());
            }

//            } else {
//                ToastUtil.showToast(getContext(), resources.getString(R.string.countMan));
//            }
        } else {
            if (null != rw && machine_id != "") {
                createProgressDialog(resources.getString(R.string.keeping));

                mPresenter.insertSProductionInfo(sTime,
                        rw.getZbid(), rw.getRdsno(), rw.getOrderno(), rw.getCustid(), sTime, rw.getPartid(),
                        rw.getPrdid() + "", Double.parseDouble(et_should_num.getText().toString()), rw.getCode(),
                        inpter, userid + "", machine_id, mName, inputerName, rw.getProcno(), getStype(), getMoreCom()
                );
            } else {
                ToastUtil.showToast(getContext(), resources.getString(R.string.wo_num_hint));
            }
        }

    }

    private String getEditText(EditText editText) {
        return editText.getText().toString();
    }

    private int getTextInt(EditText editText) {
        String text = editText.getText().toString();
        return Integer.valueOf(text.toString().isEmpty() ? "0" : text);
    }

    private void queryWO() {

        if (btn_inpter.getText().toString().equals(resources.getString(R.string.btn_ok_inputer))) {
            et_inputer.setFocusable(true);
            if (et_inputer.getText().toString().isEmpty()) {
                new EditTextShakeTool(getContext()).shake(et_inputer);
                et_inputer.setFocusable(true);
            } else {
                createProgressDialog(resources.getString(R.string.querying));
                inpuer = et_inputer.getText().toString();
                mPresenter.queryUserIsExist(et_inputer.getText().toString());
            }
        } else if (btn_inpter.getText().toString().equals(resources.getString(R.string.wo_mobify))) {
            emptyEt();
            et_inputer.setFocusable(true);
            et_inputer.setFocusableInTouchMode(true);
            btn_inpter.setText(resources.getString(R.string.btn_ok_inputer));
            et_inputer.setText("");
        }
    }

    @Override
    public String getName() {
        return null;
    }

    @Override
    public String getCode() {
        return null;
    }


    @Override
    public String getStype() {
        String stype = mySetting.getString("rCode", "");
        Log.d(TAG, "getStype: " + stype);
        return stype;
    }

    @Override
    public String getMoreCom() {
        String moreCom = mySetting.getString("rMoreCom", "");
//        Log.d(TAG, "getMoreCom: "+moreCom);
        return moreCom;
    }

    @Override
    public void queryISuccess(Inputer inputer) {
        mProgressDialog.cancel();
        et_inputer.setFocusable(false);
        et_inputer.setFocusableInTouchMode(false);
        workSP.edit().putString("inputer", inpuer).commit();
        workSP.edit().putString("inputerName", inputer.getData().get(0).getName()).commit();

//        Log.d(TAG, "queryISuccess: "+workSP.getString("inputer",""));
        isInputer = true;
        et_inputer.setText(et_inputer.getText().toString() + inputer.getData().get(0).getName());
        btn_inpter.setText(resources.getString(R.string.wo_mobify));
    }

    @Override
    public void queryIFail(String failMsg) {
//        if (mProgressDialog.isShowing()) {
        mProgressDialog.cancel();
//        }
        ToastUtil.showToast(getActivity(), failMsg);
        isInputer = false;
        new EditTextShakeTool(getActivity()).shake(et_inputer);
    }

    //扫描工单二维码出现的数据
    @Override
    public void queryWSuccess(WorkOrder2 workOrder) {
        mProgressDialog.cancel();
        if (null == workOrder.getData()) {
            ToastUtil.showToast(getContext(), workOrder.getInfo());
        } else {
            mProgressDialog.cancel();
            et_work_order_id.setFocusableInTouchMode(false);
            et_work_order_id.setFocusable(false);
            workSP.edit().putString("work_id", work_id).commit();
            isWorkId = true;
            WorkOrder2.DataBeanX.DataBean dataEntity = workOrder.getData().getData().get(0);
            id = dataEntity.getId();
            realHandleWorkOrder = new ArrayList<>();
            workSP.edit().putString("procno", dataEntity.getProcno()).commit();
            et_work_order_id.setText(dataEntity.getRdsno());
            et_order_id.setText(dataEntity.getOrderno());
            et_cust_name.setText(dataEntity.getCustName());
            et_partId.setText(dataEntity.getPartid());
            et_procedure.setText(dataEntity.getProcName());
            et_product_name.setText(dataEntity.getProdName());
            et_should_num.setText(dataEntity.getReqnumb() + "");//车头数
            et_already_num.setText(dataEntity.getFNumb() + "");//已生产数
//        本工序的車頭數(最大)=上工序完成數*(本工序應產數/上工序良品數)
//
//        本次的車頭數=本工序的車頭數(最大)-已生產數
//
//        未生產餘數=應生產數-已生數-本次的車頭數

//        reqnumb	fNumb	finishnumb	allowNumb
//       150	   0.00	      0        	0	         100

            //curfnumb上工序已完成数
            //getFNumb本工序已完成数
            isOver = dataEntity.getIsOver();
            thisAllow = 0;//dataEntity.getAllowNumb() - alreadyNum;
            alreadyNum = Integer.valueOf(dataEntity.getFNumb());
            nofinishNum = dataEntity.getReqnumb() - alreadyNum;//getReqnumb-getFNumb
            thisAllow = dataEntity.getAllowNumb() - alreadyNum;
            sheetNumb = dataEntity.getSheetNumb();
            realHandleWorkOrder.add(dataEntity);
            et_no_finish_num.setText(nofinishNum + "");//未生产余数
            procno = dataEntity.getProcno();
//        isPrintVisviable(dataEntity.getIsPrint());
//            String groupName = dataEntity.getGroupName();
            String rdsno = dataEntity.getRdsno();
            String partid = dataEntity.getPartid();
            String reProce = dataEntity.getProdName();
            //对领料进行判断
//            mPresenter.getMaterial(rdsno,partid,groupName,reProce);
        }
    }


    String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        return date;
    }

    @Override
    public void queryWFail(String failMsg) {
        mProgressDialog.cancel();
        isWorkId = false;
        ToastUtil.showToast(getContext(), failMsg);
    }

    @Override
    public void findMSuccess(MachineInfo machineInfo) {
        mProgressDialog.cancel();
        workSP.edit().putString("machine_id", machine_id).commit();
        isMachineInfo = true;
        et_machine_id.setText("(" + machineInfo.getData().get(0).getName() + ")");
        et_machine_id.setFocusable(false);
        et_machine_id.setFocusableInTouchMode(false);
        barZbid = machineInfo.getData().get(0).getProddailyid();
        Log.d(TAG, "findMSuccess: " + isExist);
        if (!machineInfo.getData().get(0).getStarttime().equals("")
                && machineInfo.getData().get(0).getEndtime().equals("")) {

            isExist = true;
            clickControl(isExist);
            et_e_time.setText(getCurrentTime());
            et_s_time.setText(machineInfo.getData().get(0).getStarttime());
            long eTime = System.currentTimeMillis();
            workSP.edit().putLong("eTime", eTime).commit();
        } else {
            isExist = false;
//            isExist=true;
            clickControl(isExist);
            et_s_time.setText(getCurrentTime());
            long sTime = System.currentTimeMillis();
            workSP.edit().putLong("sTime", sTime).commit();
        }

    }

    private void clickControl(boolean isExist) {
        et_produce_num.setClickable(isExist);
        et_produce_num.setFocusable(isExist);
        et_produce_num.setEnabled(isExist);
        et_produce_num.setFocusableInTouchMode(isExist);
//        et_people_group.setEnabled(isExist);
//        et_people_group.setClickable(isExist);
//        et_people_group.setFocusable(isExist);
//        et_people_group.setFocusableInTouchMode(isExist);
//
//        et_team_group.setEnabled(isExist);
//        et_team_group.setClickable(isExist);
//        et_team_group.setFocusable(isExist);
//        et_team_group.setFocusableInTouchMode(isExist);


//        add_item.setClickable(isExist);
//        bt_w_delete.setEnabled(isExist);
//        add_item.setVisibility((isExist ? View.VISIBLE : View.GONE));

    }

    public void clickSet(EditText editText, boolean isclik) {
        editText.setClickable(isclik);
        editText.setFocusable(isclik);
        editText.setEnabled(isclik);
        editText.setFocusableInTouchMode(isclik);
    }


    @Override
    public void findMFail(String failMsg) {

        mProgressDialog.cancel();
        isMachineInfo = false;
        ToastUtil.showToast(getContext(), failMsg);
    }

    @Override
    public void updateTSSuccess(UpdateInfo updateInfo) {

    }

    @Override
    public void updateTSFail(String fail) {

    }


    //班组人组查询结果
    @Override
    public void findWPSuccess(final PDistrubition pDistrubition) {
        pdistrubition = new ArrayList<>();
        for (PDistrubition.DataBeanX.DataBean pd : pDistrubition.getData().getData()) {
            pdistrubition.add(pd);
            Log.d(TAG, "keepTheData: ddd" + pd.getCode() + ":" + pd.getName());
        }

        mProgressDialog.cancel();
        adapter = new ZZWorkAdapter(getContext());
        adapter.addContext(getContext());
        adapter.addItems(pdistrubition);
        itemRemoveRecycleView.setAdapter(adapter);
        itemRemoveRecycleView.setOnItemClickListener(new ItemRemoveRecycleView.ItemOnListener() {
            @Override
            public void onItemDelete(int position) {

                adapter.removeItem(position);
                pdistrubition.remove(position);
                itemRemoveRecycleView.removeViewAt(position);

            }
        });

    }

    @Override
    public void findWPFail(String fail) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), fail);
    }

    @Override
    public void insertSPSuccess(UpdateInfo info) {
        mProgressDialog.cancel();
        emptyEt();
        et_inputer.setText(mySetting.getString("mCode", ""));
        et_machine_id.setText(machine_code);
        ToastUtil.showToast(getContext(), info.getInfo());
    }

    @Override
    public void insertSPFail(String fail) {

        mProgressDialog.cancel();

        ToastUtil.showToast(getContext(), fail);
    }

    @Override
    public void insertEPSuccess(UpdateInfo info) {
        mProgressDialog.cancel();
        emptyEt();
        machine_code = "";
        et_inputer.setText(mySetting.getString("mCode", ""));
        ToastUtil.showToast(getContext(), info.getInfo());
    }

    @Override
    public void insertEPFail(String fail) {
        mProgressDialog.cancel();

        ToastUtil.showToast(getContext(), fail);
    }

    @Override
    public void getMaterialSuccess(RequstMaterial requstMaterial) {
//        ToastUtil.showToast(getContext(),requstMaterial.getInfo());
    }

    @Override
    public void getMaterialFail(String fail) {
//        ToastUtil.showToast(getContext(),fail);
    }


    private void emptyEt() {
        workSP.edit().clear().commit();
        et_inputer.setText("");
        et_inputer.setFocusableInTouchMode(true);
        et_inputer.setFocusable(true);
        btn_inpter.setText(resources.getString(R.string.btn_ok_inputer));
        id = 0;
        et_work_order_id.setText("");
        et_work_order_id.setFocusableInTouchMode(true);
        et_work_order_id.setFocusable(true);
        et_s_time.setText("");
        et_e_time.setText("");
        et_machine_id.setText("");
        et_machine_id.setFocusableInTouchMode(true);
        et_machine_id.setFocusable(true);
        et_order_id.setText("");
        et_cust_name.setText("");
        et_partId.setText("");
        et_procedure.setText("");
        et_already_num.setText("");
        et_produce_num.setEnabled(false);
        et_produce_num.setText("");
        et_product_name.setText("");
        et_should_num.setText("");
        et_no_finish_num.setText("");
//        et_people_group.setText("");
//        et_team_group.setText("");


        if (null != adapter && pdistrubition.size() > 0) {
//        if (null != adapter) {

            adapter.deleteItems(pdistrubition);
            adapter = null;
            pdistrubition = null;
        }

        cb_is_finish.setChecked(false);
        isInputer = false;
        isMachineInfo = false;
        isWorkId = false;
    }

    private void setEditTextEmpty(EditText editText) {

        editText.setEnabled(false);
        editText.setText("");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        workSP.edit().clear().commit();
        realHandleWorkOrder = null;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    public void text() {

    }
}
